using System;
using System.Diagnostics;
using System.Reflection;
using NUnit.Framework;

namespace Universe.Farm.Tests
{
    [TestFixture]
    public class TestIntegrityCheck
    {
        [Test]
        public void Test_Each_Algorithm()
        {
            
            CommunicationParameters.CommunicationIntegrityAlgorithm[] algs = 
                (CommunicationParameters.CommunicationIntegrityAlgorithm[]) Enum.GetValues(typeof (CommunicationParameters.CommunicationIntegrityAlgorithm));

            foreach (CommunicationParameters.CommunicationIntegrityAlgorithm alg in algs)
            {
                IBufferProtocol bp = GetBP(alg);
                Trace.WriteLine(alg);
                Random rand = new Random(0);
                for (int len = 0; len < 100000; len = (len + 1) * 2)
                {
                    byte[] arg = new byte[len];
                    rand.NextBytes(arg);

                    byte[] encoded = bp.Encode(arg);
                    byte[] copy = bp.Decode(encoded);

                    Assert.AreEqual(arg, copy, "Algorithm {0}, Length is {1}", alg, len);
                }
                
            }
        }

        IBufferProtocol GetBP(CommunicationParameters.CommunicationIntegrityAlgorithm alg)
        {
            Type t = typeof (Service.Farm).Assembly.GetType("Universe.Farm.Service.BufferProtocol");
            ConstructorInfo ci = t.GetConstructor(new Type[] {typeof (CommunicationParameters.CommunicationIntegrityAlgorithm)});
            object raw = ci.Invoke(new object[] {alg});
            return (IBufferProtocol) raw;
        }

        
    }
}
